//
//  COLevelViewController.swift
//  CocoProject
//
//  Created by Ruthless on 2023/8/29.
//

import UIKit

class COLevelViewController: COBaseViewController {
    private var contents: [FoodType] = [.italy, .france, .usa, .russia, .britain, .thailand, .japan, .other]
    private var select: [FoodType] = []
    
    var level: String = ""
    
    var image: UIImage?
    var age: Int?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
    
    override func configUI() {
        view.addSubview(nameLabel)
        view.addSubview(beginner)
        view.addSubview(intermediate)
        view.addSubview(advanced)
        view.addSubview(foodLabel)
        view.addSubview(collectionView)
        view.addSubview(doneButton)
        view.addSubview(skipButton)
        
        nameLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.top.equalToSuperview().offset(67+statusBarHeight)
        }
        
        beginner.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(26)
            make.top.equalTo(nameLabel.snp.bottom).offset(35)
        }
        
        intermediate.snp.makeConstraints { make in
            make.centerY.equalTo(beginner)
            make.centerX.equalToSuperview()
        }
        
        advanced.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-26)
            make.centerY.equalTo(beginner)
        }
        
        foodLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.top.equalTo(beginner.snp.bottom).offset(50)
        }
        
        collectionView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(22)
            make.top.equalTo(foodLabel.snp.bottom).offset(25)
            make.height.equalTo(78)
        }
        
        doneButton.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(18)
            make.height.equalTo(50)
            make.bottom.equalTo(skipButton.snp.top).offset(-25)
        }
        
        skipButton.snp.makeConstraints { make in
            make.bottom.equalToSuperview().offset(-99-bottomSafeHeight)
            make.centerX.equalToSuperview()
        }
    }
    
    private lazy var nameLabel: UILabel = {
        let label = UILabel()
        label.font = .bold(20)
        label.textColor = .white
        label.text = "Professional level"
        return label
    }()

    private lazy var beginner: COLevelView = {
        let view = COLevelView("Beginner")
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(selectLevel))
        view.addGestureRecognizer(tap)
        view.isUserInteractionEnabled = true
        return view
    }()
    
    private lazy var intermediate: COLevelView = {
        let view = COLevelView("Intermediate")
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(selectLevel))
        view.addGestureRecognizer(tap)
        view.isUserInteractionEnabled = true
        return view
    }()
    
    private lazy var advanced: COLevelView = {
        let view = COLevelView("Advanced")
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(selectLevel))
        view.addGestureRecognizer(tap)
        view.isUserInteractionEnabled = true
        return view
    }()
    
    private lazy var foodLabel: UILabel = {
        let label = UILabel()
        label.font = .bold(20)
        label.textColor = .white
        label.text = "Favorite western food"
        return label
    }()
    
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: (SCREENWIDTH-36-40)/4, height: 33)
        layout.minimumLineSpacing = 12
        layout.minimumInteritemSpacing = 10
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .rgba(17, 7, 41, 1)
        cv.delegate = self
        cv.dataSource = self
        cv.register(cellWithClass: COCreateCollectionViewCell.self)
        return cv
    }()
    
    private lazy var doneButton: UIButton = {
        let btn = UIButton()
        let bgLayer1 = CAGradientLayer()
        bgLayer1.colors = [UIColor.rgba(218, 67, 255).cgColor, UIColor.rgba(82, 28, 255).cgColor]
        bgLayer1.locations = [0, 1]
        bgLayer1.frame = CGRect(x: 0, y: 0, width: SCREENWIDTH-36, height: 50)
        bgLayer1.startPoint = CGPoint(x: 1, y: 0.56)
        bgLayer1.endPoint = CGPoint(x: 0.56, y: 0.56)
        btn.layer.insertSublayer(bgLayer1, at: 0)
        
        btn.setTitle("Done", for: .normal)
        btn.titleLabel?.font = .medium(14)
        btn.setTitleColor(.white, for: .normal)
        
        btn.layer.masksToBounds = true
        btn.layer.cornerRadius = 25
        
        btn.addTarget(self, action: #selector(clickButton), for: .touchUpInside)
        return btn
    }()
    
    private lazy var skipButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("Skip", for: .normal)
        btn.setTitleColor(.white.withAlphaComponent(0.5), for: .normal)
        
        btn.addTarget(self, action: #selector(clickButton), for: .touchUpInside)
        return btn
    }()
}

class COLevelView: UIStackView {
    var sel: Bool {
        get {
            return true
        }
        set {
            button.isSelected = newValue
            nameButton.isSelected = newValue
        }
    }
    init(_ level: String) {
        super.init(frame: .zero)
        
        axis = .vertical
        spacing = 8
        alignment = .center
        button.setImage(UIImage(named: level), for: .normal)
        nameButton.setTitle(level, for: .normal)
        
        configUI()
    }
    
    required init(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func configUI() {
        addArrangedSubviews([button, nameButton])
        button.snp.makeConstraints { make in
            make.width.height.equalTo(84)
        }
    }
    
    private lazy var button: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIColor.rgba(41, 32, 63, 1).toImage(), for: .normal)
        btn.setBackgroundImage(UIImage(named: "椭圆形 4"), for: .selected)
        btn.layer.masksToBounds = true
        btn.layer.cornerRadius = 42
        
        btn.isUserInteractionEnabled = false
        return btn
    }()
    
    private lazy var nameButton: UIButton = {
        let btn = UIButton()
        btn.setTitleColor(.white, for: .normal)
        btn.setTitleColor(.rgba(152, 48, 255, 1), for: .selected)
        btn.titleLabel?.font = .regular(12)
        
        btn.isUserInteractionEnabled = false
        return btn
    }()
}

extension COLevelViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let type = contents[indexPath.row]

        if select.contains(type) {
            select.removeAll { item in
                item == type
            }
        } else {
            select.append(type)
        }
        
        collectionView.reloadData {
            
        }
    }
}

extension COLevelViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        contents.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withClass: COCreateCollectionViewCell.self, for: indexPath)
        let type = contents[indexPath.row]
        cell.button.setTitle(type.tag, for: .normal)
//        cell.addLayer(select == type)
        cell.addLayer(select.contains(type))
        return cell
    }
}

extension COLevelViewController {
    @objc
    private func clickButton(_ btn: UIButton) {
        if btn == skipButton {
            self.navigationController?.popToRootViewController(animated: true)
        } else if btn == doneButton {
            uploadImage()
        }
    }
    
    @objc
    private func selectLevel(_ tap: UITapGestureRecognizer) {
        guard let view = tap.view as? COLevelView else {
            return
        }
        
        if view == beginner {
            if level != "Beginner" {
                level = "Beginner"
            } else {
                level = ""
            }
        }
        
        if view == intermediate {
            if level != "Intermediate" {
                level = "Intermediate"
            } else {
                level = ""
            }
        }
        
        if view == advanced {
            if level != "Advanced" {
                level = "Advanced"
            } else {
                level = ""
            }
        }
        
        beginner.sel = level == "Beginner"
        intermediate.sel = level == "Intermediate"
        advanced.sel = level == "Advanced"
    }
    
    private func uploadImage() {
        self.view.makeToastActivity(.center)
        if let image = image {
            CONetwork.sendRequest(provider: homeProvider, target: .uploadImage(image: image)) { text in
                let photo = text.replacingOccurrences(of: "\"", with: "")
                self.updateMessage(photo)
            } failedBlock: { _, text in
                self.view.hideToastActivity()
                self.view.makeToast(text, position: .center)
            }
        } else {
            updateMessage("")
        }
        
    }
    
    private func updateMessage(_ image: String) {
        CONetwork.sendRequest(provider: loginProvider, target: .complete(sculpture: image, age: age, level: level, food: select.map({ item in
            "\(item.rawValue)"
        }).joined(separator: ","))) { text in
            self.view.hideToastActivity()
            guard let userInfo = COUserManager.userInfo else {
                return
            }
            
            if !image.isEmpty {
                userInfo.sculpture = image
            }
            if let age = self.age {
                userInfo.age = age
            }
            
            userInfo.level = self.level
            userInfo.food = self.select.map({ item in
                "\(item.rawValue)"
            }).joined(separator: ",")
            COUserManager.userInfo = userInfo
            
            self.navigationController?.popToRootViewController(animated: true)
        } failedBlock: { _, text in
            self.view.hideToastActivity()
            self.view.makeToast(text, position: .center)
        }

    }
}
